// pages/home/home.js
import {
  apiUrl
} from '@/api/request'
import {
  getshopinfo,
  spaProjectList,
  shopcollect,
  spaList,
  submitSpaBooking,
  verifyMemberPoints,
  getBookingInfo
} from '@/api/spa'
import {
  showText
} from "../../utils/util";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUri: getApp().globalData.imgUri,
    cdn: getApp().globalData.cdn,
    swiperindex: 0,
    detail: {},
    dataArr: [1, 2, 3, 4, 5],
    project: [],
    spaListInfo: {},
    collected: false,
    consumeNum: 0,
    collectNum: 0,
    absId: 0,
    spaId: 0,
    bookingId: 0,
    latitude: 0,
    longitude: 0,
    is_yuyue: 0, //0 未预约 1已兑换 2已预约
    showPopup: false,
    getgemomemberuser:{}, // 用户信息
    // avatarUrl: getApp().globalData.imgUri + '/my/avatarUrl.png',
    avatarUrl: '',
    nickName: 'GEMO会员',
    show3: false,
    show4: false,
    show10: false,
    show11: false,
    exchange_flag: false,

    showToast: false,
    toastText: ['您还未获得GEMO臻享护理券', '购买任意GEMO正装仪器即刻获取'],
    shopImg:[],
    shopImgCurrent:0,
    my_absId:0,
    my_spaId:0,
    // 查看我的预约弹框 
    showMyBook:false,
    is_status:1,
  },
  // 前往我的预约
  confirmMyBook(){
    wx.navigateTo({
      url: '/pages/bookSuccess/bookSuccess',
    })
  },
  closeDialog(){
    this.setData({
      showMyBook:false
    })
  },
  findImages(e){
    let { index } = e.currentTarget.dataset
    let list = this.data.detail.shopImg.map(r=>{
      return this.data.cdn+r.src
    })
    console.log(list,index)
    wx.previewImage({
      urls: list,
      current: list[index]
    })
  },
  makePhoneCall() {
    wx.makePhoneCall({
      phoneNumber: '' + this.data.detail.shopTel,
    })
  },
  openAuthPopup() {
    this.setData({
      showPopup: true
    })
  },
  closeAuth(e) {
    console.log(e)
    this.setData({
      showPopup: false
    })
  },
  swiperChange(e) {
    this.setData({
      swiperindex: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getBannerImgInfo(new_shopImg){
    let t = this;
    if(new_shopImg[t.data.shopImgCurrent]){
      wx.getImageInfo({
        src: new_shopImg[t.data.shopImgCurrent].img,
        success: function(res) {
          new_shopImg[t.data.shopImgCurrent].width = res.width;
          new_shopImg[t.data.shopImgCurrent].height = res.height;
          var shopImgCurrent = t.data.shopImgCurrent + 1;
          t.setData({
            shopImgCurrent:shopImgCurrent
          });
          t.getBannerImgInfo(new_shopImg);
        }
      });
    }else{
      t.setData({
        shopImg:new_shopImg,
      });
      console.log(t.data.shopImg);
    }
  },
  onLoad(options) {
    let t = this;
    if (options.absId) {
      var absId = options.absId;
      var spaId = options.spaId;
      var latitude = options.latitude;
      var longitude = options.longitude;
      t.setData({
        absId: absId,
        spaId: spaId,
        latitude: latitude,
        longitude: longitude,
      });
      getshopinfo({
        absId: absId,
        latitude: latitude,
        longitude: longitude,
      }).then(res => {
        if (res.code == 200) {
          var data = res.data;
          data.distance = Math.round(data.distance / 1000);
          var shopImg = data.shopImg;
          if(shopImg){
            const systemInfo = wx.getSystemInfoSync();
            var width = systemInfo.windowWidth;
            var height = systemInfo.windowHeight;
            if(shopImg.indexOf("[") >= 0){
              var arr_shopImg = JSON.parse(shopImg);//shopImg.split(",");
              for(var i=0;i<arr_shopImg.length;i++){
                var img_width = arr_shopImg[i].width;
                var img_height = arr_shopImg[i].height;

                var img_heigh_new = (img_height / img_width) * width;
                if(img_width >= img_height){
                  var img_margin_top = 0;
                }else{
                  var img_margin_top = (250 - img_heigh_new) / 2;
                }
                arr_shopImg[i].img_margin_top = img_margin_top;
              }
            }else{
              arr_shopImg = "";
            }
            data.shopImg = arr_shopImg;
          }
          /*
          if(shopImg){
            var new_shopImg = [];
            var arr_shopImg = shopImg.split(",");
            for(var i=0;i<arr_shopImg.length;i++){
              new_shopImg.push({"img":t.data.cdn+arr_shopImg[i],"width":0,"height":0});
            }
            t.getBannerImgInfo(new_shopImg);
          }

           */
          t.setData({
            detail: data,
            collected: data.collected,
            consumeNum: data.consumeNum,
            collectNum: data.collectNum,
          });

          t.f_spaProjectList();


        }
      });

    }
  },
  f_spaProjectList(){
    let t = this;
    spaProjectList(t.data.spaId).then(res => {
      if (res.code == 200) {
        var data = res.data;
        var is_status = 1;
        for (var i = 0; i < data.length; i++) {
          var status = data[i].status;
          if(status){
            if (i == 0) {
              var num = "疗程一";
            } else if (i == 1) {
              var num = "疗程二";
            } else if (i == 2) {
              var num = "疗程三";
            } else if (i == 3) {
              var num = "疗程四";
            } else if (i == 4) {
              var num = "疗程五";
            } else if (i == 5) {
              var num = "疗程六";
            }
          }else{
            is_status = 0;
            var num = "";
          }

          data[i].num = num;
        }
        t.setData({
          project: res.data,
          is_status:is_status,
        });
        t.f_spaList();
      }
    });
  },
  f_spaList(){
    let t = this;
    spaList().then(res => {
      if (res.code == 200) {
        let spaListInfo = {};
        for (var i = 0; i < res.data.length; i++) {
          if (t.data.spaId == res.data[i].id) {
            spaListInfo = res.data[i];
          }
        }
        t.setData({
          spaListInfo: spaListInfo
        });
        t.f_getBookingInfo();
      }
    });
  },
  f_getBookingInfo(){
    let t = this;
    getBookingInfo({}).then(res => {
      console.log(res);
      if (res.code == 200) {
        var data = res.data;
        var mobile = data.bookingInfo.mobile;
        var bookingId = data.bookingInfo.id;
        var my_absId = data.bookingInfo.shopId;
        var my_spaId = data.bookingInfo.spaId;
        if (mobile) {
          var is_yuyue = 2;
        } else {
          var is_yuyue = 1;
        }
        t.setData({
          bookingId: bookingId,
          my_absId: my_absId,
          my_spaId: my_spaId,
        });
      } else { //未预约
        var is_yuyue = 0;
      }
      t.setData({
        is_yuyue: is_yuyue,
      });
      t.f_verifyMemberPoints();
    });
  },
  f_verifyMemberPoints(){
    let t = this;
    let utm_source = wx.getStorageSync('utm_source');
    if(utm_source){
      t.setData({
        exchange_flag: true
      });
    }else{
      verifyMemberPoints().then(res => {
        if (res.code == 200) {
          t.setData({
            exchange_flag: res.data.exchange_flag
          });
        }
      });
    }
  },
  closeToast() {
    this.setData({
      showToast: false
    })
  },
  openLocation() {
    let {
      latitude,
      longitude,
      shopName
    } = this.data.detail
    wx.openLocation({
      latitude,
      longitude,
      name: shopName || '',
      complete: (com) => {
        console.log(com)
      }
    })
  },
  goToBook() {
    let t = this;
    let spaId = t.data.spaId;
    let absId = t.data.absId;
    let my_absId = t.data.my_absId;
    let my_spaId = t.data.my_spaId;
    let bookingId = t.data.bookingId;
    let is_yuyue = t.data.is_yuyue;
    var getgemomemberuser = wx.getStorageSync('getgemomemberuser');
    var avatarUrl = getgemomemberuser.avatarUrl;
    var nickName = getgemomemberuser.nickName;
    var familyName = getgemomemberuser.familyName;
    var givenName = getgemomemberuser.givenName;
    var gender = getgemomemberuser.gender;
    if (!avatarUrl) {
      t.openAuthPopup();
      return false;
    }
    this.setData({
      getgemomemberuser
    })


    let params = {
      avatarUrl: t.data.cdn + avatarUrl,
      spaName: t.data.spaListInfo.name,
      spaId: t.data.spaId,
      absId: t.data.absId,
      bookingId: bookingId,
    };

    if (familyName) {
      params.familyName = familyName+givenName;

    } else {
      params.familyName = nickName;
    }
    if (is_yuyue == 0) { //未预约
      if (!t.data.exchange_flag) {
        // showText('您还未获得GEMO臻享护理券\n购买任意GEMO正装仪器即刻获取')
        this.setData({
          showToast: true
        })
        return false;
      }else{
        t.setData({
          params,
          show4: true
        });
      }

    } else if (is_yuyue == 1) { //已兑换
      t.setData({
        params,
        show3: true
      });
    } else if (is_yuyue == 2) { //预约成功
      if(spaId == my_spaId && absId == my_absId){
        wx.navigateTo({
          url: '/pages/bookSuccess/bookSuccess',
        })
      }else{
        t.setData({
          showMyBook: true
        });
      }
    }
  },
  cli_collected() {
    let t = this;
    var collectNum = t.data.collectNum;
    var collected = t.data.collected;
    if (collected == false) {
      var collected_new = true;
      collectNum++;
    } else {
      var collected_new = false;
      collectNum--;
    }
    shopcollect({
      absId: t.data.absId,
      collect: collected_new
    }).then(res => {
      if (res.code == 200) {
        t.setData({
          collected: collected_new,
          collectNum: collectNum,
        })

      }
    });
  },
  cli_project(e) {
    let t = this;
    let {
      content,
      title,
      num,
      status
    } = e.currentTarget.dataset
    if(!status){
      return false;
    }
    var params = {
      content: content,
      title: title,
      num: num
    };
    t.setData({
      params,
      show11: true
    })
  },
  closeProp3() {
    this.setData({
      show3: false
    })
  },
  successProp3(params) {
    this.setData({
      params,
      show3: false
    }, () => {

    });
  },
  closeProp4(e) {
    let t = this;
    let type = e.detail
    var getgemomemberuser = wx.getStorageSync('getgemomemberuser');
    var avatarUrl = getgemomemberuser.avatarUrl;
    var nickName = getgemomemberuser.nickName;
    var familyName = getgemomemberuser.familyName;
    var gender = getgemomemberuser.gender;

    let params = {
      avatarUrl: t.data.cdn + avatarUrl,
      spaName: t.data.spaListInfo.name,
      spaId: t.data.spaId,
      absId: t.data.absId,
    };

    if (familyName) {
      params.familyName = familyName;
      params.gender = gender + "士";
    } else {
      params.familyName = nickName;
      params.gender = "";
    }
    let p = {
      shopId: t.data.absId,
      spaId: t.data.spaId
    };
    let utm_source = wx.getStorageSync('utm_source');
    if(utm_source){
      p.ignorePointCheck = true;
    }
    if (type == 'show3') {
      submitSpaBooking(p).then(res => {
        if (res.code == 200) {
          params.bookingId = res.data.bookingId;
          t.setData({
            bookingId: res.data.bookingId,
            is_yuyue: 1,
            params,
            show3: true
          })
        } else {
          showText(res.msg)
        }
      });
    }
    this.setData({
      params,
      show4: false
    })
  },
  successProp4(params) {
    this.setData({
      show4: false
    }, () => {

    });
  },
  closeProp10() {
    this.setData({
      show10: false
    })
  },
  successProp10(params) {
    this.setData({
      show10: false
    }, () => {

    });
  },
  closeProp11() {
    this.setData({
      show11: false
    })
  },
  successProp11(params) {
    this.setData({
      show11: false
    }, () => {

    });
  },
  // 设置头像
  setAvatarUrl(e) {
    console.log(e)
    this.setData({
      avatarUrl: e.detail
    })
    let url = apiUrl + '/file/uploadFile'
    // 上传图片
    wx.uploadFile({
      filePath: e.detail,
      name: 'file',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('access_token')
      },
      url: url,
      success: (res) => {
        let res1 = JSON.parse(res.data)
        console.log(res1.data.url)
        this.setData({
          avatarUrl: getApp().globalData.cdn + res1.data.url
        })
      },
      fail: (err) => {
        console.log('Url:', url, ' err:', err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: getApp().globalData.share_title,
      path: getApp().globalData.share_url,
      imageUrl: getApp().globalData.share_image,
    }
  }
})